package com.jiacl.service.impl;

import com.jiacl.core.CommonConstants;
import com.jiacl.core.CommonConstants.ErrorCode;
import com.jiacl.entity.JiaclFamilySeniority;
import com.jiacl.entity.core.Result;
import com.jiacl.exception.BusinessException;
import com.jiacl.mapper.JiaclFamilySeniorityMapper;
import com.jiacl.service.FamilySeniorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by XiaoWei on 2017/9/2.
 */
@Service
public class FamilySeniorityServiceImpl implements FamilySeniorityService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private JiaclFamilySeniorityMapper jiaclFamilySeniorityMapper;
    @Override
    public Result selectFamilySeniorityServiceByArea(Long areaId) {
        if(areaId<=0){
            return new Result();
        }
        Object redisCache = redisTemplate.opsForValue().get(CommonConstants.FAMILY_SENIORITY_REDIS_KEY + areaId);
        if(redisCache!=null){
            return new Result(redisCache);
        }
        List<JiaclFamilySeniority> jiaclFamilySeniorities = jiaclFamilySeniorityMapper.selectJiaclFamilySeniorityMapper(areaId);
        redisTemplate.opsForValue().set(CommonConstants.FAMILY_SENIORITY_REDIS_KEY+areaId,jiaclFamilySeniorities,1, TimeUnit.DAYS);
        return new Result(jiaclFamilySeniorities);
    }

    @Override
    public Result addFamilySeniorityServiceByArea(JiaclFamilySeniority jiaclFamilySeniority) {
        if(StringUtils.isEmpty(jiaclFamilySeniority.getAreaId())){
            throw new BusinessException(ErrorCode.ERROR_SENIORITY_AREA_ERROR);
        }
        if (StringUtils.isEmpty(jiaclFamilySeniority.getSernameId())){
            throw new BusinessException(ErrorCode.ERROR_SENIORITY_ERROR);
        }
        jiaclFamilySeniorityMapper.insertSelective(jiaclFamilySeniority);
        return new Result();
    }
}
